<?php

function revisit_list_page()
{
    @$output = drupal_render(drupal_get_form('revisit_list_form'));
    return $output;
}
function revisit_list_form($form, &$form_state)
{
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if(!empty($form_state['addr_id'])){
        $form['#addr_id'] = $form_state['addr_id'];
    }
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if(!empty($form_state['farmer'])){
        $form['#farmer'] = $form_state['farmer'];
    }

    if(empty($form_state['farmer'])&& empty($form['#addr_id'])){
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
        $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
    }
    $fields = array(
        '' => '请选择',
        'unit_yield' => '单产量',
        'net_income' => '纯收益',
        'contrast_yield' => '对照产量',
        'contrast_income' => '对照收益'
    );
    numerical_range_search($form,$fields);
    if(!empty($_GET['special_activities'])){
        $special_activities_title = get_special_activities_title($_GET['special_activities']);
    }
    $form['special_activities'] = array(
        '#type' => 'textfield',
        '#title' => '专项活动',
        '#size' => 32,
        '#maxlength' => 50,
        '#id'=>'special_activities_textfield',
        '#default_value' => $special_activities_title,
    );
//    $form['visit_date'] = array(
//        '#type' => 'date',
//        '#default_value' =>  _date_db_2_form(!empty($record) ? $record->visit_date : ''),
//    );
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : "";
    $init_month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : "";
    _insert_date_selection_form($form, $form_state, 5, $init_year, $init_month);
    $form['plant'] = _insert_plant_selection_form($form,$form_state,'');
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function revisit_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
        array('data' => '地址', 'class' => ['essential province city county']),
        array('data' => '回访日期', 'class' => ['essential province city county'],'field' => 'visit_date'),
        isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
            array('data' => '农户', 'class' => ['essential store-name']),
        array('data' => '农作物', 'class' => ['essential more']),
        array('data' => '单产量', 'class' => ['essential more']),
        array('data' => '纯收益', 'class' => ['essential more']),
        array('data' => '对照产量', 'class' => ['essential more']),
        array('data' => '对照收益', 'class' => ['essential more']),
        array('data' => '操作', 'class' => ['essential more']),
    );
    $output = '';
    $query = db_select('revisit', 'R')->extend('PagerDefault')->extend('TableSort');
    $query->join('farmer', 'F', 'F.farmer_id=R.farmer_id');
    $query->join('plant', 'P', 'P.plant_id=R.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    //地址级别查询
    _address_search_conditon($query,$form_state);
    if (!empty($form_state['values']['plant'])) {//村落级
        $query->condition('R.plant_id',get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false), '=');
    }
    if (!empty($form_state['values']['farmer_id'])) {//
        $query->condition('R.farmer_id', $form_state['values']['farmer_id'], '=');
    }
    if(!empty($_GET['farmer_id'])){
        $query->condition('R.farmer_id',$_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {//
        $query->condition('R.farmer_id', $form_state['farmer'], '=');
    }
    if (!empty($form_state['addr_id'])) {//
        $query->condition('F.addr_id', $form_state['addr_id'], '=');
    }
    if ($user_info['role'] != '农户') {
        if (!user_access('view all revisit') && user_access('view own revisit')) {
            $query->condition('R.author_uid', $user->uid, '=');
        }
    }
    //专项活动
    if(!empty($form_state['values']['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('R.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('R.special_activities_id',0, '=');
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('R.special_activities_id',$_GET['special_activities'], '=');
    }
    $datestr = '';
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $datestr .= $form_state['values']['year'] . '-';
        }
    }
    if (!empty($form_state['values']['month'])) {//查询条件
        if ($month = $form_state['values']['month']) {
            if ($month < 10)
                $datestr .= '0' . $form_state['values']['month'];
            else
                $datestr .= $form_state['values']['month'];
        }
    }

    if ($datestr) {
        $query->condition('R.visit_date','%'. db_like($datestr) . '%', 'LIKE');
    }

    if(!empty($form_state['values']['field'])){
        if(!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])){
            $db_and = db_and();
            $db_and->condition('R.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('R.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        }elseif(!empty($form_state['values']['min_number'])){
            $query->condition('R.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
        }elseif(!empty($form_state['values']['max_number'])){
            $query->condition('R.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    $query->fields('R');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'addr_id');
    $query->addField('P', 'plant_name');
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('R.timestamp', 'DESC');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $revisitInfo = $query->orderByHeader($header)->execute();
    $rows = array();
    //表内容
    $n = 1;
    foreach ($revisitInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        $town = $row->town ? ' ' . $row->town : '';
        $village = $row->village ? ' ' . $row->village : '';
        if (nonghua_user_access('revisit', 'delete', $row->revisit_id, $row->author_uid,  $row->farmer_id)) {
            $disabled = ' class="listViewTableCheck" ';
        } else{
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => "<input type='checkbox'".$disabled." value ='" . $row->revisit_id . "' name='" . $row->revisit_id . "'/>" . $n++, 'class' => 'integrant essential no'),
            isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
            array('data' =>$row->province . $city . $county.$town.$village, 'class' => ['integrant essential province city county']),
            array('data' => $row->visit_date , 'class' => ['integrant haveTobr essential province city county']),
            isset($form_state['farmer']) && !empty($form_state['farmer'])?"":
            array('data' =>'<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id='.$row->farmer_id.'">' . $row->farmer_name.'</a>', 'class' => ['integrant essential store-name']),
            array('data' => $row->plant_name, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->unit_yield, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->net_income, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->contrast_yield, 'class' => ['integrant goRight essential phone']),
            array('data' => $row->contrast_income, 'class' => ['integrant goRight essential phone']),
            (isset($form_state['farmer']) && !empty($form_state['farmer']))||(isset($form_state['addr_id']) && !empty($form_state['addr_id']))?
                array('data' => '<a href="' . base_path() . 'revisit/edit/' . $row->revisit_id .'?'.
                    (isset($form_state['addr_id']) && !empty($form_state['addr_id'])?'addr_id='.$form_state['addr_id'].'&':'').
                    (isset($form_state['farmer']) && !empty($form_state['farmer'])?'farmer_id='.$form_state['farmer']:'').
                    '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>','class' => 'essential more'):
                array('data' => '<a href="' . base_path() . 'revisit/edit/' . $row->revisit_id . '" data-toggle="modal" target="_self"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own revisit') ||  user_access('delete all revisit'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'revisit/export?'.$str.'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&plant='.$form_state['values']['plant'].'&special_activities='.$form_state['values']['special_activities'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}
function revisit_delete()
{
    ajax_table_delete('revisit', 'revisit_id');
}

function revisit_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','农户','农作物','回访日期','单产量','纯收益','对照产量','对照收益','回访内容');
    $data = get_revisit_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'回访信息数据');
}

function get_revisit_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('revisit', 'R');
    $query->join('farmer', 'F', 'F.farmer_id=R.farmer_id');
    $query->join('plant', 'P', 'P.plant_id=R.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    //地址级别查询
    if (!empty($_GET['village'])) {//村落级
        $query->condition('A.village_id', $_GET['village'], '=');
    } else if (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id', $_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    if (!empty($_GET['plant'])) {//村落级
        $query->condition('R.plant_id',$_GET['plant'], '=');
    }
    if (!empty($_GET['farmer_id'])) {//
        $query->condition('R.farmer_id', $_GET['farmer_id'], '=');
    }
    if(!empty($_GET['farmer_id'])){
        $query->condition('R.farmer_id',$_GET['farmer_id']);
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {//
        $query->condition('R.farmer_id', $form_state['farmer'], '=');
    }
    if (!empty($form_state['addr_id'])) {//
        $query->condition('F.addr_id', $form_state['addr_id'], '=');
    }
    if ($user_info['role'] != '农户') {
        if (!user_access('view all revisit') && user_access('view own revisit')) {
            $query->condition('R.author_uid', $user->uid, '=');
        }
    }
    //专项活动
    if(!empty($_GET['special_activities'])){
        $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$_GET['special_activities'],false);
        if(!empty($special_activities_id)){
            $query->condition('R.special_activities_id',$special_activities_id, '=');
        }else{
            $query->condition('R.special_activities_id',0, '=');
        }
    }
    $datestr = '';
    if (!empty($_GET['year'])) {//查询条件
        if ($_GET['year']) {
            $datestr .= $_GET['year'] . '-';
        }
    }
    if (!empty($_GET['month'])) {//查询条件
        if ($month = $form_state['values']['month']) {
            if ($month < 10)
                $datestr .= '0' . $_GET['month'];
            else
                $datestr .= $_GET['month'];
        }
    }
 
    if ($datestr) {
        $query->condition('R.visit_date','%'. db_like($datestr) . '%', 'LIKE');
    }

    if(!empty($_GET['field'])){
        if(!empty($_GET['min_number']) && !empty($_GET['max_number'])){
            $db_and = db_and();
            $db_and->condition('R.'.$_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('R.'.$_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        }elseif(!empty($_GET['min_number'])){
            $query->condition('R.'.$_GET['field'], $_GET['min_number'], '>');
        }elseif(!empty($_GET['max_number'])){
            $query->condition('R.'.$_GET['field'], $_GET['max_number'], '<');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    $query->fields('R',array('visit_date','unit_yield','net_income','contrast_yield','contrast_income','content'));
    if(empty($form_state['values'])){
        $query->orderBy('R.timestamp', 'DESC');
    }

    $revisitInfo = $query->execute()->fetchAll();
    foreach($revisitInfo as $k => $v){
        $revisitInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($revisitInfo[$k]->city);
        unset($revisitInfo[$k]->county);
        unset($revisitInfo[$k]->town);
        unset($revisitInfo[$k]->village);
    }
    return $revisitInfo;
}